import ctypes

if '__main__' == __name__:

    xdata = [
        ['小泉纯一郎', '小犬'],
        ['毛泽东', '润之'],
        [None, None],
        ['毛泽东', '毛主席'],
        ['习近平', None],
        ['刘备', '大耳'],
        [None, '习近平'],
        ['刘皇叔', '刘玄德'],
        ['刘备', '刘玄德'],
        ['金三胖', '金正恩'],
        [None, '金正日'],
        ['金正日', '金二胖'],
    ]

    num2set_map = dict()

    for xpair in xdata:
        x, y = xpair
        print('>>>', x, y)

        set_x = num2set_map.get(x, None)
        set_y = num2set_map.get(y, None)

        if x is None and y is None:
            continue
        elif y is None:
            if set_x is not None:
                continue
            else:
                print(x, '->', 'set(', x, ')')
                num2set_map[x] = set([x])
                continue
        elif x is None:
            if set_y is not None:
                continue
            else:
                print(y, '->', 'set(', y, ')')
                num2set_map[y] = set([y])
                continue

        # x is not None and y is not None

        if set_x is None and set_y is None:
            print(x, '-> set(', x, y, ')')
            print(y, '-> set(', x, y, ')')
            set_xy = set([x, y])
            num2set_map[y] = set_xy
            num2set_map[x] = set_xy
            continue
        elif set_y is None:
            set_x.add(y)
            print(y, '-> ', set_x)
            num2set_map[y] = set_x
            continue
        elif set_x is None:
            set_y.add(x)
            print(x, '-> ', set_y)
            num2set_map[x] = set_y
            continue
        else:
            if set_x == set_y:  # already associated
                print(x, y, 'already associated')
                continue
            else:
                print(set_x, 'union', set_y)
                set_xy = set_x.union(set_y)
                print('=>', set_xy)
                for xnum in set_xy:
                    print(xnum, '->', set_xy)
                    num2set_map[xnum] = set_xy

    print('Result')
    xsets_ids = set()
    xmap_id2set = {}
    for xset in num2set_map.values():
        xid = id(xset)
        xsets_ids.add(xid)
        xmap_id2set[xid] = xset

    xsets = []
    for xid in xsets_ids:
        xset = xmap_id2set[xid]
        xsets.append(tuple(xset))

    xresult = sorted(xsets)
    for xtup in xresult:
        print(xtup)
